package org.water.common.util;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * request 工具
 * @author qzy
 *
 */
public class RequestUtil {

	/**
	 * 获取请求参数
	 * @param request
	 * @param name 请求参数，如果为空则返回""
	 * @return
	 */
	public static String getParam(HttpServletRequest request,String name)
	{
		return request.getParameter(name);
	}
	/**
	 * 获取请求参数
	 * @param request
	 * @param name 请求参数，如果为空则返回null
	 * @return
	 */
	public static String getParamNull(HttpServletRequest request,String name)
	{
		String value=request.getParameter(name);
		if("".equals(value)) value=null;
		return value;
	}
	/**
	 * 获取请求参数
	 * @param request
	 * @return
	 */
	public static JSONArray getParams(HttpServletRequest request)
	{
		JSONArray params=new JSONArray();
		Enumeration<String> methodParameters =request.getParameterNames();
		while(methodParameters.hasMoreElements())
		{
			String paramName=methodParameters.nextElement();
			JSONObject obj=new JSONObject();
			obj.put(paramName, request.getParameter(paramName));
			params.add(obj);
		}
		return params;
	}
	/**
	 * 获取请求参数
	 * @param request
	 * @return
	 */
	public static String getParamStr(HttpServletRequest request)
	{
		return getParams(request).toJSONString();
	}
	/**
	 * 参数转义操作，防止xss功击
	 * @param request
	 * @param paramName
	 * @return
	 */
	public static String escapeParam(HttpServletRequest request,String paramName)
	{
		String value="";
		value=request.getParameter(paramName);
		StringEscapeUtils.escapeHtml4(value);
		StringEscapeUtils.escapeEcmaScript(value);
		StringEscapeUtils.escapeJava(value);
		return value;
	}
}
